package com.geek.novel.dialog

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.geek.novel.R
import com.geek.novel.activity.TypefaceActivity
import com.geek.novel.activity.book.BookSettingsActivity
import com.geek.novel.activity.book.CrawlerSourceActivity
import com.geek.novel.activity.book.ViewerActivity
import com.geek.novel.common.Constant
import com.geek.novel.fragment.BookMenuFragmentFactory
import com.geek.novel.fragment.FragmentLightSetting
import com.geek.novel.fragment.FragmentReadSetting
import com.geek.novel.ui.ReadView
import com.geek.novel.utils.FormatUtil
import com.geek.novel.utils.SPUtil
import com.zackratos.ultimatebarx.ultimatebarx.addStatusBarTopPadding
import skin.support.SkinCompatManager
import skin.support.observe.SkinObserver


/**
 * 底部菜单的弹框
 */
class ViewerMenuDialog(private val mContext: ViewerActivity, private val sectionView: ReadView) :CustomDialog(mContext) {

    //切换主题按钮
    private lateinit var btnReadMenuTheme: ImageView

    /**标题弹框的控件容器*/
	private lateinit var titleBar: ViewGroup
    /**菜单弹框的控件容器*/
    private lateinit var menuDialog: ViewGroup

	/**阅读设置的容器*/
	private var fragmentReadSetting: FragmentReadSetting? = null

	/**亮度设置的容器*/
	private var fragmentLightSetting: FragmentLightSetting? = null

	/**顶部标题栏右边菜单的弹框*/
	private var bookReadMenuDialog: BookReadMenuDialog? = null

	/**初始化容器控件*/
	@SuppressLint("InflateParams")
	override fun initDialogViews(parent: ViewGroup): List<View> {
		val views = ArrayList<View>()
		//加载弹出框的布局
		menuDialog = LayoutInflater.from(this.context).inflate(R.layout.dialog_book_menu, null) as ViewGroup
		val lp = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
		lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE)
        parent.addView(menuDialog, lp)
		views.add(menuDialog)
		
		//加载弹出框的布局
		titleBar = LayoutInflater.from(this.context).inflate(R.layout.dialog_book_title, null) as ViewGroup
		val lp2 = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
        parent.addView(titleBar, lp2)
		views.add(titleBar)
		
		return views
	}
	
    override fun initDialog() {
        //切换主题按钮
        btnReadMenuTheme = getMenuView(R.id.btn_read_menu_theme) as ImageView
        btnReadMenuTheme = getMenuView(R.id.btn_read_menu_theme) as ImageView

		//绑定换肤的观察者
		SkinCompatManager.getInstance().addObserver(skinObserver)

		//显示主题按钮
        this.refreshThemeButton()

        //初始化fragment布局
        this.initFragment()

		//初始化弹框
		bookReadMenuDialog = BookReadMenuDialog(mContext)

        //绑定标题信息
        this.initTitleBar()

    }
	
	/**创建fragment工厂*/
	private val bookMenuFragmentFactory = BookMenuFragmentFactory(sectionView)

    /**初始化fragment布局*/
    private fun initFragment(){
		mContext.supportFragmentManager.fragmentFactory = bookMenuFragmentFactory
		this.showMenuSetting()
    }
	
	/**显示菜单设置*/
	private fun showMenuSetting(){
		if(fragmentReadSetting == null){
			fragmentReadSetting = FragmentReadSetting.newInstance(sectionView)
		}
		mContext.replaceFrag(R.id.fragment_container_viewer_menu, fragmentReadSetting!!)
	}

	/**显示亮度设置*/
	private fun showLightSetting(){
		if(fragmentLightSetting == null){
			fragmentLightSetting = FragmentLightSetting.newInstance()
		}
		mContext.replaceFrag(R.id.fragment_container_viewer_menu, fragmentLightSetting!!)
	}

	/**绑定标题信息*/
	private fun initTitleBar(){
		val titleBar = getTitleView(R.id.ly_viewer_title_bar)
		titleBar.addStatusBarTopPadding()
		bindTitleOnClickEvent(R.id.btn_viewer_title_back)
		bindTitleOnClickEvent(R.id.btn_viewer_title_menu)
		val titleView = getTitleView(R.id.tv_viewer_title_text) as TextView
		context as ViewerActivity
		if(context.book != null){
			titleView.text = context.book!!.bookName
		}
	}

	/**换肤监听*/
	private val skinObserver = SkinObserver { _, _ ->
		this.refreshThemeButton()
	}


    /**显示主题按钮*/
    private fun refreshThemeButton(){
        val curSkinName = SkinCompatManager.getInstance().curSkinName
        //显示图标为太阳或者月亮
        val icon = if(Constant.Theme_Night == curSkinName) R.drawable.icon_sun else R.drawable.icon_moon
        btnReadMenuTheme.setImageDrawable(mContext.getDrawable(icon))
    }

    /**
     * 切换主题
     */
    private fun toggleTheme(){
		val curSkinName = SkinCompatManager.getInstance().curSkinName
        if(Constant.Theme_Night == curSkinName){//当前为黑色主题，回复为之前的主题
			val theme = SPUtil[SPUtil.app_current_theme, "", SPUtil.SP_SYSTEM_SETUP] as String
			if(TextUtils.isEmpty(theme)){
				//恢复默认皮肤
				SkinCompatManager.getInstance().restoreDefaultTheme()
			}else{//恢复为之前保存的主题
				SkinCompatManager.getInstance().loadSkin(theme, null, SkinCompatManager.SKIN_LOADER_STRATEGY_BUILD_IN)
			}
        } else{
			//记录当前颜色
			SPUtil.put(SPUtil.app_current_theme, curSkinName, SPUtil.SP_SYSTEM_SETUP)
            //切换皮肤名为night的皮肤
            SkinCompatManager.getInstance().loadSkin(Constant.Theme_Night, null, SkinCompatManager.SKIN_LOADER_STRATEGY_BUILD_IN)
        }
    }

    /**绑定事件*/
	override fun bindEvent() {
        //顶部的菜单容器的点击事件
        this.bindMenuOnClickEvent(R.id.ly_menu_top_container)
        //切换主题
        btnReadMenuTheme.setOnClickListener(this)
	
		//绑定图标按钮事件
		this.bindMenuOnClickEvent(R.id.viewer_menu_item_list)
		this.bindMenuOnClickEvent(R.id.viewer_menu_item_book_setting)
		this.bindMenuOnClickEvent(R.id.viewer_menu_item_light)
		this.bindMenuOnClickEvent(R.id.viewer_menu_item_setting)
		
        //选择字体按钮事件
        this.bindMenuOnClickEvent(R.id.btn_read_menu_typeface)
	
		//换源按钮事件
        this.bindMenuOnClickEvent(R.id.btn_read_menu_crawler_source)
    }

    /**绑定点击事件*/
    private fun bindMenuOnClickEvent(id: Int){
		getMenuView(id).setOnClickListener(this)
    }

    /**绑定点击事件*/
    private fun bindTitleOnClickEvent(id: Int){
		getTitleView(id).setOnClickListener(this)
    }
	
	private fun getMenuView(id: Int): View{
		return menuDialog.findViewById(id)
	}
	
	private fun getTitleView(id: Int): View{
		return titleBar.findViewById(id)
	}

	/**设置高亮*/
	private fun resetMenuItemActive(curId: Int){
		val idList = arrayListOf(R.id.viewer_menu_item_book_setting, R.id.viewer_menu_item_light)
		val srcList = arrayListOf(R.drawable.icon_setting_2_grey, R.drawable.icon_light_grey)
		val srcActiveList = arrayListOf(R.drawable.icon_setting_2, R.drawable.icon_light)
		for (i in 0 until idList.size) {
			val view = getMenuView(idList[i]) as ImageView
			if(idList[i] == curId){
				view.setImageResource(srcActiveList[i])
			}else{
				view.setImageResource(srcList[i])
			}
		}
	}
	

    /**
     * 点击事件
     */
    override fun clickEvent(id: Int, v: View) {
        when(id){
            //顶部的菜单容器的点击事件
            R.id.ly_menu_top_container->{
                this.close()
            }
            //切换主题
            R.id.btn_read_menu_theme->{
                this.toggleTheme()
            }
            //更换字体
            R.id.btn_read_menu_typeface->{
				mContext.startActivityForResultByAnim(mContext, TypefaceActivity::class.java, Constant.ACTIVITY_RESULT_TYPEFACE)
            }
            //换源
            R.id.btn_read_menu_crawler_source->{
				context as ViewerActivity
				val params = Bundle()
				params.putString("bookId", context.book!!.bookId)
				mContext.startActivityForResultByAnim(mContext, CrawlerSourceActivity::class.java, params, Constant.ACTIVITY_RESULT_CRAWLER_SOURCE)
            }
            //标题栏点击后退
            R.id.btn_viewer_title_back->{
				mContext.finish()
            }
            //标题栏点击菜单
            R.id.btn_viewer_title_menu->{
				val position = IntArray(2)
				v.getLocationOnScreen(position)//获取控件的坐标
				val x = FormatUtil.isNullToIntZero(position[0]).toFloat()
				val y = FormatUtil.isNullToIntZero(position[1]).toFloat() + v.height
				bookReadMenuDialog!!.openDialog(Gravity.NO_GRAVITY, x, y)
            }
			//打开章节列表
			R.id.viewer_menu_item_list->{
				this.close()
				mContext.sendHandlerMessage(Constant.handler_event_open_section_index_dialog)
			}
			//阅读设置
			R.id.viewer_menu_item_book_setting->{
				this.resetMenuItemActive(id)
				this.showMenuSetting()
			}
			//亮度调整
			R.id.viewer_menu_item_light->{
				resetMenuItemActive(id)
				this.showLightSetting()
			}
			//更多设置
			R.id.viewer_menu_item_setting->{
				mContext.startActivityForResultByAnim(mContext, BookSettingsActivity::class.java, Constant.ACTIVITY_RESULT_BOOK_SETTING)
			}
        }
    }
	
	override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when(requestCode){
            //从字体选择页面返回的
            Constant.ACTIVITY_RESULT_TYPEFACE->{
                //设置字体，重绘页面
                this.sectionView.setPaintTypeface()
                this.sectionView.postInvalidate()
            }
			//从换源页面返回
			Constant.ACTIVITY_RESULT_CRAWLER_SOURCE->{
				mContext.reCrawlerBookIndex()
			}
			//从阅读设置页面返回
			Constant.ACTIVITY_RESULT_BOOK_SETTING->{
//				mContext.reCrawlerBookIndex()
			}
        }
    }


	/**销毁时、移除控件的监听*/
	override fun onDestroy() {
		super.onDestroy()
		//移除监听器
		SkinCompatManager.getInstance().deleteObserver(skinObserver)
	}
	
	override fun open() {
		this.sectionView.onHide()
		//加载章节标题信息
		if(fragmentReadSetting != null){
			fragmentReadSetting!!.initSectionTitle()
		}
		//用动画的形式打开dialog
		this.openDialogAnim(arrayListOf(R.anim.push_up_in, R.anim.viewer_title_in))
	}
	
	override fun close() {
		this.sectionView.onShow()
		this.closeDialogAnim(arrayListOf(R.anim.push_down_out, R.anim.viewer_title_out))
	}

}